package com.cardone.common.util;

import com.cardone.common.function.ReadDictionaryNameByTypeCodeAndCodeFunction;
import com.cardone.context.CodeException;
import com.cardone.context.ContextHolder;
import com.cardone.context.Contexts;
import com.google.common.collect.Maps;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * 返回数据
 *
 * @author yaohaitao
 */
@Slf4j
public class ReturnDataUtils {
    @Setter
    private static String defaultErrorMessage = "系统错误";

    private ReturnDataUtils() {
    }

    /**
     * 生成
     *
     * @param data 数据
     * @return 返回数据
     */
    public static Map<String, Object> newMap(final Object data) {
        return newMap(Contexts.data.stringValue(), data);
    }

    /**
     * 生成
     *
     * @param e 导常
     * @return 返回数据
     */
    public static Map<String, String> newErrorMap(final Throwable e) {
        return newErrorMap(null, e);
    }

    /**
     * 生成
     *
     * @param request 导常
     * @param e       导常
     * @return 返回数据
     */
    public static Map<String, String> newErrorMap(String request, final Throwable e) {
        log.error(e.getMessage(), e);

        Map<String, String> errorMap = Maps.newHashMap();

        errorMap.put("request", request);

        if (e instanceof CodeException) {
            CodeException codeException = (CodeException) e;

            errorMap.put("error_code", codeException.getCode());

            String error = ContextHolder.getBean(ReadDictionaryNameByTypeCodeAndCodeFunction.class).execution(StringUtils.defaultIfBlank(codeException.getMessage(), codeException.getCode()), "error_code", codeException.getCode());

            errorMap.put("error", error);
        } else {
            if (log.isDebugEnabled()) {
                errorMap.put("error_code", "debug");
                errorMap.put("error", e.getMessage());
            } else {
                errorMap.put("error_code", "100001");
                errorMap.put("error", StringUtils.defaultIfBlank(defaultErrorMessage, e.getMessage()));
            }
        }

        return errorMap;
    }

    /**
     * 生成
     *
     * @param data 数据
     * @return 返回数据
     */
    public static Map<String, Object> newMap(String key, final Object data) {
        Map<String, Object> map = Maps.newHashMap();

        String newKey = StringUtils.defaultIfBlank(key, Contexts.data.stringValue());

        map.put(newKey, data);

        return map;
    }
}
